#include "project.h"

bool FontManager::loadFont(const std::string& fontPath) {
    std::ifstream file(fontPath, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "❌ 无法打开字库文件: " << fontPath << std::endl;
        return false;
    }

    file.seekg(0, std::ios::end);
    size_t size = file.tellg();
    file.seekg(0, std::ios::beg);

    fontData.resize(size);
    file.read(reinterpret_cast<char*>(fontData.data()), size);

    // 🔴 关键：检查是否读取成功
    if (file.gcount() != static_cast<std::streamsize>(size)) {
        std::cerr << "❌ 读取不完整！期望: " << size << " 字节, 实际: " << file.gcount() << std::endl;
        fontData.clear();
        file.close();
        return false;
    }

    file.close();

    // ✅ 打印前 10 字节，验证是否真有数据
    std::cout << "✅ 字库加载成功: " << fontPath << " (" << size << " 字节)" << std::endl;
    std::cout << "🔍 fontData 前 10 字节: ";
    for (int i = 0; i < 10 && i < fontData.size(); ++i) {
        std::cout << std::hex << (int)fontData[i] << " ";
    }
    std::cout << std::dec << std::endl;

    return true;
}

const unsigned char* FontManager::getCharBitmap(char c) {
    if (fontData.empty()) return nullptr;

    int ascii = static_cast<unsigned char>(c);
    if (ascii < 0x20 || ascii > 0x7E) {
        ascii = '?'; // 替代字符
    }

    int index = ascii - 0x20; // .DZK 中从空格开始
    size_t offset = index * 32; // 每个字符 32 字节

    if (offset + 32 > fontData.size()) {
        return nullptr;
    }

    return &fontData[offset];
}